package com.xjtu.mybatisplus.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xjtu.mybatisplus.common.JsonResponse;
import com.xjtu.mybatisplus.mapper.UserMapper;
import com.xjtu.mybatisplus.model.domain.Category;
import com.xjtu.mybatisplus.model.domain.Subscribe;
import com.xjtu.mybatisplus.mapper.SubscribeMapper;
import com.xjtu.mybatisplus.model.domain.User;
import com.xjtu.mybatisplus.model.dto.EmailDto;
import com.xjtu.mybatisplus.model.vo.SubNoticeVo;
import com.xjtu.mybatisplus.model.vo.SubscribeVo;
import com.xjtu.mybatisplus.service.CategoryService;
import com.xjtu.mybatisplus.service.EmailService;
import com.xjtu.mybatisplus.service.SubscribeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * ���� 服务实现类
 * </p>
 *
 * @author lsong
 * @since 2023-12-27
 */
@Service
@Slf4j
public class SubscribeServiceImpl extends ServiceImpl<SubscribeMapper, Subscribe> implements SubscribeService {

    @Autowired
    SubscribeMapper subscribeMapper;

    @Autowired
    CategoryService categoryService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    EmailService emailService;
    @Override
    public JsonResponse getStatus(Long userId, Long categoryId) {
        if(userId <= 0 || categoryId <= 0){
            return JsonResponse.failure("意外的用户/栏目");
        }

        QueryWrapper<Subscribe> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("category_id", categoryId);
        return subscribeMapper.selectCount(wrapper) > 0 ? JsonResponse.success(1):JsonResponse.success(0);
    }

    @Override
    public JsonResponse setStatus(Long userId, Long categoryId, boolean status) {
        if(userId <= 0 || categoryId <= 0){
            return JsonResponse.failure("意外的用户/栏目");
        }
        if(status){
            Subscribe subscribe = new Subscribe();
            subscribe.setUserId(userId).setCategoryId(categoryId);
            return subscribeMapper.insert(subscribe) > 0 ? JsonResponse.success(1): JsonResponse.failure("更新失败");
        }
        QueryWrapper<Subscribe> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId).eq("category_id", categoryId);
        return subscribeMapper.delete(wrapper) > 0 ?   JsonResponse.success(0): JsonResponse.failure("更新失败");

    }

    @Override
    public JsonResponse<List<SubscribeVo>> getList(Long userId) {
        if(userId <= 0) {
            return JsonResponse.failure("意外的用户");
        }
        List<SubscribeVo> subscribes = subscribeMapper.getList(userId);
        if(subscribes.size() == 0){
            return JsonResponse.success(null);
        }
        return JsonResponse.success(subscribes);
    }

    public boolean generateNotice(SubNoticeVo subNoticeVo, List<Long> userIds) {
        System.out.println("发布内容为："+subNoticeVo);
        List<String> tos = new ArrayList<>();
        for(Long userId : userIds){
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.select("email").eq("id", userId);
            List<User> users = userMapper.selectList(wrapper);
            User user = users.get(0);
            if(user.getEmail() == null){
                continue;
            }
            tos.add(user.getEmail());
        }
        log.info("11{}",tos);
        EmailDto emailDto = new EmailDto();
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("subscribe-notice.ftl");

        emailDto.setTos(tos);
        emailDto.setSubject("订阅提醒通知");
        emailDto.setContent(template.render(Dict.create().set("categoryName", subNoticeVo.getCategoryName()).set("title", subNoticeVo.getTitle()).set("articleId",subNoticeVo.getArticleId())));

        try {
        emailService.send(emailDto);
        log.info("邮件按理来说发送成功");
            return true;
        } catch (Exception e){
            log.warn(e.getMessage());
            log.info("发送失败");
            return false;
        }
    }
}
